import {defineStore} from 'pinia';
import {Http, Cache, Helper, Msg, Constant} from 'core';
import Base64 from '@/util/base64.js';
const store = {
    id: "user",
    state(){
        return {
            user: {},
			roles: [],
			permissions: []
        }
    },

    getters: {

    },

    actions: {
        setUser(user, roles, permissions) {
            this.user = user;
            this.roles = roles;
            this.permissions = permissions;
        },

		getUser() {
			return Helper.emptyJson(this.user) ? {} : this.user;
		},

		getRole() {
			return Helper.emptyArray(this.roles) ? [] : this.roles;
		},

		hasRole(roleCode) {
        	return Helper.emptyArray(this.roles) ? false : this.roles.indexOf(roleCode) > -1
		},

		async login(authCode) {
			Msg.loading("加载中...")
			Cache.setToken("");
			let {code, message, data} = await Http.post("/oauth2/token?grant_type=mobile", {'mobile': 'APP_HOUSE_COMMUNITY@' + authCode})
				.addHeaders("Skiptoken", true)
				.addHeaders("Content-type", "application/x-www-form-urlencoded")
				.addHeaders("Authorization", "Basic " + Base64.encoder("app:app"))
				.setInterceptor(null, (response) => {
					let res = {};
					if(! Helper.empty(code)) {
						res = {code: 500, message: response.data.msg, data: response.data};
					} else {
						res = {code: 0, message: "调用成功", data: response.data};
					}
					response.data = res;
				})
			Msg.loading(false);
			if(code == 200) {
				//读取用户信息
				Cache.setToken(data.access_token);
				await this.brief();
				return true;
			}

			return false;
		},

		async brief() {
			this.user = {};
			Msg.loading("加载中...");
			let {code, data} = await Http.get("/appuser/info");
			Msg.loading(false);
			if(code == 200) {
				let user = data.appUser;
				let roles = data.roles;
				let permissions = data.permissions;
				this.setUser(user, roles, permissions);
			}

			return this.user;
		},

		/**
		 * 解密电话号码并绑定用户信息
		 * @param encryptedData
		 * @param name
		 * @returns {Promise<string|string|*>}
		 */
		async encrypted(encryptedData, name) {
        	Msg.loading("加载中...")
			let {code, data} = await Http.post("/appuser/phone/encrypted", {encryptedData, name})
        	Msg.loading(false)
			if(code == 200) {
				return Helper.empty(data) ? "" : data;
			}
			return "";
		},

		async check() {
			return await Http.post("/user/check/token").validate(false);
		},

		async logout() {
			await Http.create("/token/logout").setMethod("delete");
		}
    }
}

export default defineStore(store)
